import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import Layout from '@/views/Layout.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresAuth: false, title: '注册' }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true, title: '首页' },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { requiresAuth: true, title: '仪表盘', affix: true }
      },
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { requiresAuth: true, title: '个人中心' }
      },
      {
        path: '/user/list',
        name: 'UserList',
        component: () => import('@/views/user/UserList.vue'),
        meta: { permission: 'system:user:list', title: '用户管理' }
      },
      {
        path: '/user/profile',
        name: 'UserProfile',
        component: () => import('@/views/Profile.vue'),
        meta: { requiresAuth: true, title: '个人中心' }
      },
      {
        path: '/system/role',
        name: 'RoleManage',
        component: () => import('@/views/system/RoleManage.vue'),
        meta: { permission: 'system:role:view', title: '角色管理' }
      },
      {
        path: '/system/menu',
        name: 'MenuManage',
        component: () => import('@/views/system/MenuManage.vue'),
        meta: { permission: 'system:menu:view', title: '菜单管理' }
      },
      {
        path: '/system/log',
        name: 'LogManage',
        component: () => import('@/views/system/LogManage.vue'),
        meta: { permission: 'system:log:list', title: '操作日志' }
      },
      {
        path: '/system/dict',
        name: 'DictManage',
        component: () => import('@/views/system/DictManage.vue'),
        meta: { permission: 'system:dict:list', title: '字典管理' }
      },
      {
        path: '/system/organization',
        name: 'OrganizationManage',
        component: () => import('@/views/system/OrganizationManage.vue'),
        meta: { permission: 'system:organization:view', title: '组织管理' }
      },
      {
        path: '/notification/list',
        name: 'NotificationList',
        component: () => import('@/views/notification/NotificationList.vue'),
        meta: { permission: 'system:notification:list', title: '通知列表' }
      },
      {
        path: '/notification/send',
        name: 'SendNotification',
        component: () => import('@/views/notification/SendNotification.vue'),
        meta: { permission: 'system:notification:send', title: '发送通知' }
      },
      {
        path: '/chat',
        name: 'ChatList',
        component: () => import('@/views/chat/ChatList.vue'),
        meta: { requiresAuth: true, title: '聊天' }
      }
    ]
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile.vue'),
    meta: { requiresAuth: true, title: '个人中心' }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/403.vue'),
    meta: { requiresAuth: false, title: '无权限' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token

  // 如果访问登录或注册页面，直接放行
  if (to.path === '/login' || to.path === '/register') {
    // 如果已登录，跳转到首页
    if (token) {
      next('/dashboard')
    } else {
      next()
    }
    return
  }

  // 如果访问403页面，直接放行
  if (to.path === '/403') {
    next()
    return
  }

  // 如果需要认证且没有token，跳转到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  } 
  
  // 检查权限（只有已登录且页面需要特定权限时才检查）
  if (token && to.meta.permission) {
    const hasPermission = userStore.hasPermission(to.meta.permission)
    if (!hasPermission) {
      ElMessage.error('您没有访问该页面的权限')
      next('/403')
      return
    }
  }
  
  next()
})

export default router